package com.yc.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.yc.entity.User;
import com.yc.mapper.ClassInfoMapper;
import com.yc.mapper.StudentInfoMapper;
import com.yc.mapper.UserMapper;
import com.yc.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.yc.entity.ClassInfo;
import com.yc.service.ClassInfoService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 班级表;(class_info)表控制层
 *
 * @date : 2023-6-27
 */
@Api(tags = "班级表对象功能接口")
@RestController
@RequestMapping("/classInfo")
public class ClassInfoController {

    @Autowired
    private ClassInfoService classInfoService;

    @Resource
    private ClassInfoMapper classInfoMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @ApiOperation("通过ID查询单条数据")
    @GetMapping("{id}")
    public Result<ClassInfo> queryById(Integer id) {
        return Result.success(classInfoService.queryById(id));
    }

    /**
     * 通过班级名称查询单条数据
     *
     * @param cname 班级名称
     * @return 实例对象
     */
    @ApiOperation("通过name查询单条数据")
    @GetMapping("queryByName")
    public Result<ClassInfo> queryByName(String cname) {
        ClassInfo classInfo = classInfoMapper.queryByName(cname);
        return Result.success(classInfo);
    }

    /**
     * 分页查询
     *
     * @param classInfo 筛选条件
     * @return 查询结果
     */
    @ApiOperation("分页查询")
    @GetMapping
    public Result paginQuery(ClassInfo classInfo,
                             @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                             @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        //1.分页参数
        List<ClassInfo> classInfos = classInfoMapper.queryByPage((pageNum - 1) * pageSize, pageSize, classInfo);
        Map<String, Object> map = new HashMap<>();
        Long count = classInfoMapper.selectCount(classInfo);

        map.put("total", count);
        map.put("list", classInfos);
        return Result.success(map);
    }

    /**
     * 新增数据
     *
     * @param classInfo 实例对象
     * @return 实例对象
     */
    @ApiOperation("新增数据")
    @PostMapping("/add")
    public Result<ClassInfo> add(@RequestBody ClassInfo classInfo) {
        int result = classInfoMapper.insert(classInfo);
        if (result > 0) {
            return Result.success("插入成功");
        } else {
            return Result.error("班级信息重复");
        }
    }

    /**
     * 修改班级，辅导员工号对应信息
     *
     * @param classInfo 实例对象
     * @return 实例对象
     */
    @ApiOperation("修改数据")
    @GetMapping("/update")
    public Result update(ClassInfo classInfo) {
        int update = classInfoService.update(classInfo);
        if(update<0){
            return Result.error("班级名称重复，请取其他班级名称");
        }else {
            return Result.success("更新成功");
        }
    }

    @ApiOperation("查询所有的班级名和id")
    @GetMapping("/query")
    public Result selectAllCname(@SessionAttribute("user") User user) {
        Map<String, String> cnameResult;
        // 辅导员的权限是2，只能查询带的学生
        if (user.getRole().indexOf(2) != -1) {
            cnameResult = classInfoService.selectAllCname(user.getUsername(), null);
        } else if (user.getRole().indexOf(3) != -1){
            cnameResult = classInfoService.selectAllCname(null, user.getId() + "");
        } else{
            cnameResult = classInfoService.selectAllCname(null, null);
        }
        if (cnameResult != null || cnameResult.size() > 0) {
            return Result.success(cnameResult);
        } else {
            return Result.error("暂无信息");
        }
    }



    /**
     * 上传文件
     *
     * @param file 上传的文件对象
     * @return 实例对象
     */
    @ApiOperation("上传已经编辑好的excel信息表格")
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        int upload = classInfoService.upload(inputStream);
        if (upload == 0) {
            return Result.success("上传文件成功");
        } else {
            return Result.error("上传的文件数据第"+upload+"行有非法字符，请输入英文字符[],");
        }
    }

    /**
     * 获得所有的专业以及年级信息
     */
    @ApiOperation("获得所有的专业以及年级信息")
    @GetMapping("/getSelectInfo")
    public Result<Map<String,List<String>>> getMajorsAndYear(String teacherId){
        Map<String, List<String>> allInfo = classInfoService.getAllInfo(teacherId);
        if(allInfo!=null){
            return Result.success(allInfo);
        }else {
            return Result.error("初始化失败");
        }
    }

    @ApiOperation("通过老师ID查询上课的班级")
    @GetMapping(path = "/get/{teacherId}")
    public Result selectClassByTeacherId(@ApiParam(name = "teacherId", value = "老师Id", required = true)
                                             @PathVariable("teacherId") String teacherId){
        List<ClassInfo> classInfos = classInfoService.selectClassByTeacherId(teacherId);
        Result result = new Result(1, classInfos);
        return result;
    }

    @ApiOperation("下载模板文件")
    @GetMapping("/downLoadTemplate")
    public void downLoadTemplate(HttpServletResponse response) {
        try {
            classInfoService.downloadTemplate(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation("查年级")
    @GetMapping("/queryYearnumber")
    public Result queryYearnumber(){
        List<String> list = classInfoService.queryYearnumber();
        List<String> filteredList = list.stream()
                .filter(s -> s != null && !s.isEmpty())
                .collect(Collectors.toList());
        return Result.success(filteredList);
    }
}
